#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/fs.h"


void search(char* path,char *name){
    char buf[512],*p;
    int fd;
    struct dirent de;
    struct stat st;
    if((fd=open(path,0))<0){
        fprintf(2,"find: cannot open %s\n",path);
        return;
    }
    if(fstat(fd, &st) < 0){
        fprintf(2, "find: cannot stat %s\n", path);
        close(fd);
        return;
    }
    
    if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
        printf("find: path too long\n");
        return;
        }
    strcpy(buf, path);
    p = buf+strlen(buf);
    *p++ = '/';
    while(read(fd, &de, sizeof(de)) == sizeof(de)){
        // 剔除 .     ..
        if(de.inum==0||(!strcmp(de.name,"."))||(!strcmp(de.name,"..")))
            continue;

        memmove(p,de.name,DIRSIZ);
        p[DIRSIZ]=0;
        // 找到了 
        if(!strcmp(de.name,name)){
            
            printf("%s\n",buf);
        }

        //判断子文件是否为目录，是否需递归搜索
        if(stat(buf,&st)<0){
            printf("open: cannot stat %s\n", buf);
            continue;
        }
        if(st.type==T_DIR){
            search(buf,name);
        }
    }
    close(fd);
            
    
}



int main(int argc,char * argv[]){
    if(argc<3){
        printf("You need to enter both the search start path and the target file name\n");
        exit(0);
    }
    search(argv[1],argv[2]);
    exit(0);
}